import { getPath } from '@/utils/utils'
import { post } from './index'

// formatData 是为了适应后台的接口
function formatData(answer) {
  answer = JSON.parse(JSON.stringify(answer))
  answer.forEach(a => {
    delete a.required
  })
  return {
    survey_id: getPath(),
    answer,
  }
}
export default function (data) {
  return new Promise(async (res, rej) => {
    // 错误类型: 发送给后台了, 但是后台报错, 此时提示 FAIL; 本地前端发送报错(超时), 此时响应 ERROR
    try {
      data = formatData(data)
      const {data: resData} = await post(`/user/collect_answer`, data)
      if (resData.msg === 'success') {
        res({ status: 'success' })
        return
      }
      console.error(resData)
      rej('FAIL：' + resData.msg)
    } catch (error) {
      console.error(error)
      rej('ERROR：' + error.message)
    }
  })
}
